INCLUDE(AndroidToolchain)
INCLUDE(CMakeParseArguments)
INCLUDE(InstallPackageCommon)

MACRO(SETUP_ANDROID_BUILD_ENVIRONMENT)
    SET(ONE_VALUE_ARGS CPU_ARCH PLATFORM ANDROID_NDK_PATH)
    CMAKE_PARSE_ARGUMENTS(SETUP_ANDROID_BUILD_ENVIRONMENT "${OPTIONS}" "${ONE_VALUE_ARGS}" "${MULTI_VALUE_ARGS}" ${ARGN})
	IF(SETUP_ANDROID_BUILD_ENVIRONMENT_UNPARSED_ARGUMENTS)
		MESSAGE(FATAL_ERROR "unexpected arguments: ${SETUP_ANDROID_BUILD_ENVIRONMENT_UNPARSED_ARGUMENTS}")
	ENDIF()
	
	IF(SETUP_ANDROID_BUILD_ENVIRONMENT_CPU_ARCH)
		SET(ANDROID_SETUP_TOOLCHAIN_ARGS ${ANDROID_SETUP_TOOLCHAIN_ARGS} "CPU_ARCH" ${SETUP_ANDROID_BUILD_ENVIRONMENT_CPU_ARCH})
	ENDIF()
	IF(SETUP_ANDROID_BUILD_ENVIRONMENT_PLATFORM)
		SET(ANDROID_SETUP_TOOLCHAIN_ARGS ${ANDROID_SETUP_TOOLCHAIN_ARGS} "PLATFORM" ${SETUP_ANDROID_BUILD_ENVIRONMENT_PLATFORM})
	ENDIF()

	SET(ANDROID_NDK_VERSION "r7")
	SET(ANDROID_NDK_URL "http://dl.google.com/android/ndk/android-ndk-${ANDROID_NDK_VERSION}-linux-x86.tar.bz2")
    SET(LIBPNG_VERSION "1.5.7")
    SET(LIBPNG_URL "ftp://ftp.simplesystems.org/pub/png/src/libpng-${LIBPNG_VERSION}.tar.bz2")
    SET(LIBFREETYPE_VERSION "2.4.8")
    SET(LIBFREETYPE_URL "http://download.savannah.gnu.org/releases/freetype/freetype-${LIBFREETYPE_VERSION}.tar.bz2")

	SET(ANDROID_BUILD_ENV "${CMAKE_BINARY_DIR}/android_build_env/${CPU_ARCH}")
    FILE(MAKE_DIRECTORY ${ANDROID_BUILD_ENV})
    FILE(MAKE_DIRECTORY ${ANDROID_BUILD_ENV}/tmp)
    FILE(MAKE_DIRECTORY ${ANDROID_BUILD_ENV}/src)
	FILE(MAKE_DIRECTORY ${ANDROID_BUILD_ENV}/pkg)

	IF(NOT SETUP_ANDROID_BUILD_ENVIRONMENT_ANDROID_NDK_PATH)
		CE_UNPACK_PACKAGE("${ANDROID_BUILD_ENV}" "android_ndk" ${ANDROID_NDK_URL} "${ANDROID_BUILD_ENV}/src" SETUP_ANDROID_BUILD_ENVIRONMENT_ANDROID_NDK_PATH)
	ENDIF()

	FILE(MAKE_DIRECTORY ${ANDROID_BUILD_ENV}/pkg/android_ndk)
	ANDROID_SETUP_TOOLCHAIN(${ANDROID_SETUP_TOOLCHAIN_ARGS}
							ANDROID_NDK_PATH "${SETUP_ANDROID_BUILD_ENVIRONMENT_ANDROID_NDK_PATH}"
							OUTPUT_DIR "${ANDROID_BUILD_ENV}/pkg/android_ndk")
	IF(ANDROID_BUILD_ENVIRONMENT_CPU_ARCH STREQUAL "armv7-a")
		SET(LIBPNG_CONF_ARGS "--enable-arm-neon")
	ENDIF()
	SET(LIBFREETYPE_CONF_ARGS "LDFLAGS=--sysroot ${CMAKE_FIND_ROOT_PATH}")

    CE_INSTALL_PACKAGE(PACKAGE_ROOT "${ANDROID_BUILD_ENV}"
					   PACKAGE_NAME "libpng"
					   PACKAGE_URL "${LIBPNG_URL}"
					   CONF_ARGS "${LIBPNG_CONF_ARGS}" "--host=${ANDROID_TARGET}")
	CE_INSTALL_PACKAGE(PACKAGE_ROOT "${ANDROID_BUILD_ENV}"
					   PACKAGE_NAME "libfreetype"
					   PACKAGE_URL "${LIBFREETYPE_URL}"
					   CONF_ARGS "${LIBFREETYPE_CONF_ARGS}" "--host=${ANDROID_TARGET}")
ENDMACRO()